package com.pet.platform.controller.admin;

import com.pet.platform.common.Result;
import com.pet.platform.dto.DashboardStatsDTO;
import com.pet.platform.dto.DashboardStatsDTO.SalesTrendDTO;
import com.pet.platform.dto.DashboardStatsDTO.CategoryDistributionDTO;
import com.pet.platform.dto.OrderDTO;
import com.pet.platform.service.AppointmentService;
import com.pet.platform.service.OrderService;
import com.pet.platform.service.ProductService;
import com.pet.platform.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/api/admin/dashboard")
@RequiredArgsConstructor
@PreAuthorize("hasRole('ADMIN')")
public class AdminDashboardController {
    
    private final OrderService orderService;
    private final UserService userService;
    private final ProductService productService;
    private final AppointmentService appointmentService;

    @GetMapping("/stats")
    public Result<DashboardStatsDTO> getStats() {
        DashboardStatsDTO stats = new DashboardStatsDTO();
        
        // 设置基础统计数据
        stats.setTotalUsers(userService.count());
        stats.setTotalOrders(orderService.count());
        stats.setTotalSales(orderService.getTotalSales());
        stats.setTotalAppointments(appointmentService.count()); // 使用预约服务获取预约总数
        
        // 设置增长率（这里暂时设置为0，后续可以实现环比计算）
        stats.setUserGrowthRate(BigDecimal.ZERO);
        stats.setOrderGrowthRate(BigDecimal.ZERO);
        stats.setSalesGrowthRate(BigDecimal.ZERO);
        stats.setAppointmentGrowthRate(BigDecimal.ZERO);
        
        // 设置销售趋势数据（最近7天）
        List<SalesTrendDTO> trend = new ArrayList<>();
        LocalDate today = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd");
        
        for (int i = 6; i >= 0; i--) {
            LocalDate date = today.minusDays(i);
            SalesTrendDTO data = new SalesTrendDTO();
            data.setDate(date.format(formatter));
            data.setAmount(BigDecimal.valueOf(Math.random() * 1000).setScale(2, BigDecimal.ROUND_HALF_UP));
            trend.add(data);
        }
        stats.setSalesTrend(trend);
        
        // 设置商品类别分布数据
        List<CategoryDistributionDTO> distribution = new ArrayList<>();
        String[] categories = {"食品", "玩具", "日用品", "医疗保健", "其他"};
        for (String category : categories) {
            CategoryDistributionDTO data = new CategoryDistributionDTO();
            data.setName(category);
            data.setValue(BigDecimal.valueOf(Math.random() * 100).setScale(2, BigDecimal.ROUND_HALF_UP));
            distribution.add(data);
        }
        stats.setCategoryDistribution(distribution);
        
        return Result.success(stats);
    }

    @GetMapping("/latest-orders")
    public Result<List<OrderDTO>> getLatestOrders() {
        try {
            List<OrderDTO> latestOrders = orderService.getLatestOrders(10);
            return Result.success(latestOrders);
        } catch (Exception e) {
            // 记录错误日志
            e.printStackTrace();
            // 返回空列表而不是抛出异常
            return Result.success(new ArrayList<>());
        }
    }
} 